//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Net;
using System.Web;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security.Roles;
using System.Collections.Generic;
namespace DotNetNuke.Modules.Admin.Sales
{
	partial class PayPalIPN : Framework.PageBase
	{

		private void InitializeComponent()
		{
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			InitializeComponent();
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			try
			{
				bool blnValid = true;
				string strTransactionID;
				string strTransactionType;
				int intRoleID = 0;
				int intPortalID = PortalSettings.PortalId;
				int intUserID = 0;
				string strDescription;
				double dblAmount = 0;
				string strEmail;
				bool blnCancel = false;
				string strPayPalID = Null.NullString;
				string strResponse = Null.NullString;
				RoleController objRoles = new RoleController();
				PortalController objPortalController = new PortalController();
				string strPost = "cmd=_notify-validate";
				foreach (string strName in Request.Form)
				{
					string strValue = Request.Form[strName];
					switch (strName)
					{
						case "txn_type":
							strTransactionType = strValue;
							switch (strTransactionType)
							{
								case "subscr_signup":
								case "subscr_payment":
								case "web_accept":
									break;
								case "subscr_cancel":
									blnCancel = true;
									break;
								default:
									blnValid = false;
									break;
							}
							break;
						case "payment_status":
							if (strValue != "Completed")
							{
								blnValid = false;
							}
							break;
						case "txn_id":
							strTransactionID = strValue;
							break;
						case "receiver_email":
							strPayPalID = strValue;
							break;
						case "mc_gross":
							dblAmount = double.Parse(strValue);
							break;
						case "item_number":
							intRoleID = Int32.Parse(strValue);
							RoleInfo objRole = objRoles.GetRole(intRoleID, intPortalID);
							break;
						case "item_name":
							strDescription = strValue;
							break;
						case "custom":
							intUserID = Int32.Parse(strValue);
							break;
						case "email":
							strEmail = strValue;
							break;
					}
					strPost += string.Format("&{0}={1}", Common.Globals.HTTPPOSTEncode(strName), Common.Globals.HTTPPOSTEncode(strValue));
				}
				if (blnValid)
				{
					Dictionary<string, string> settings = PortalController.GetPortalSettingsDictionary(PortalSettings.PortalId);
                    string strPayPalURL = "";

                    // Sandbox mode
                    if(settings.ContainsKey("paypalsandbox") && !String.IsNullOrEmpty(settings["paypalsandbox"]) && settings["paypalsandbox"] == "true")
					{
                        strPayPalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?";
                    }
					else
					{
						strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?";
                    }
					HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(strPayPalURL);
					objRequest.Method = "POST";
					objRequest.ContentLength = strPost.Length;
					objRequest.ContentType = "application/x-www-form-urlencoded";
					using (StreamWriter objStream = new StreamWriter(objRequest.GetRequestStream()))
					{
                        objStream.Write(strPost);
                    }

                    using (HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse())
					{
                        using(StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
						{
							strResponse = sr.ReadToEnd();
                        }
                    }
					switch (strResponse)
					{
						case "VERIFIED":
							break;
						default:
							blnValid = false;
							break;
					}
				}
				if (blnValid)
				{
					int intAdministratorRoleId = 0;
					string strProcessorID = Null.NullString;
					PortalInfo objPortalInfo = objPortalController.GetPortal(intPortalID);
					if (objPortalInfo != null)
					{
						intAdministratorRoleId = objPortalInfo.AdministratorRoleId;
						strProcessorID = objPortalInfo.ProcessorUserId.ToLower();
					}
					if (intRoleID == intAdministratorRoleId)
					{
						strProcessorID = Host.ProcessorUserId.ToLower();
						float portalPrice = objPortalInfo.HostFee;
						if ((portalPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
						{
							objPortalController.UpdatePortalExpiry(intPortalID);
						}
						else
						{
							try
							{
								Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
								Services.Log.EventLog.LogInfo objEventLogInfo = new Services.Log.EventLog.LogInfo();
								objEventLogInfo.LogPortalID = intPortalID;
								objEventLogInfo.LogPortalName = PortalSettings.PortalName;
								objEventLogInfo.LogUserID = intUserID;
								objEventLogInfo.LogTypeKey = "POTENTIAL PAYPAL PAYMENT FRAUD";
								objEventLog.AddLog(objEventLogInfo);
							}
							catch (Exception ex)
							{
							}
						}
					}
					else
					{
						RoleInfo objRoleInfo = objRoles.GetRole(intRoleID, intPortalID);
						float rolePrice = objRoleInfo.ServiceFee;
						float trialPrice = objRoleInfo.TrialFee;
						if ((rolePrice.ToString() == dblAmount.ToString() || trialPrice.ToString() == dblAmount.ToString()) && (HttpUtility.UrlDecode(strPayPalID.ToLower()) == strProcessorID))
						{
							objRoles.UpdateUserRole(intPortalID, intUserID, intRoleID, blnCancel);
						}
						else
						{
							try
							{
								Services.Log.EventLog.EventLogController objEventLog = new Services.Log.EventLog.EventLogController();
								Services.Log.EventLog.LogInfo objEventLogInfo = new Services.Log.EventLog.LogInfo();
								objEventLogInfo.LogPortalID = intPortalID;
								objEventLogInfo.LogPortalName = PortalSettings.PortalName;
								objEventLogInfo.LogUserID = intUserID;
								objEventLogInfo.LogTypeKey = "POTENTIAL PAYPAL PAYMENT FRAUD";
								objEventLog.AddLog(objEventLogInfo);
							}
							catch (Exception ex)
							{
							}
						}
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessPageLoadException(exc);
			}
		}
	}
}
